package proTrack.auth;

import java.io.IOException;
import java.util.Map;

import javax.security.auth.Subject;
import javax.security.auth.callback.Callback;
import javax.security.auth.callback.CallbackHandler;
import javax.security.auth.callback.NameCallback;
import javax.security.auth.callback.PasswordCallback;
import javax.security.auth.callback.UnsupportedCallbackException;
import javax.security.auth.login.LoginException;

import proTrack.model.Account;


public class LoginModule implements javax.security.auth.spi.LoginModule{

	private CallbackHandler callbackHandler;
	
	private String accountName;
	
	private String password;

	private Subject subject;
		

	@Override
	public boolean abort() throws LoginException {
		System.err.println("LoginModule abort " );
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public boolean commit() throws LoginException {
		System.err.println("LoginModule commit " );
		subject.getPrincipals().add(new Account(accountName, password));
		return true;
	}

	@Override
	public void initialize(final Subject subject, final CallbackHandler callbackHandler,
			final Map<String, ?> sharedState, final Map<String, ?> options) {
		// TODO Auto-generated method stub
		System.err.println("LoginModule initialize " );
		this.callbackHandler = callbackHandler;
		this.subject = subject;
		
	}

	@Override
	public boolean login() throws LoginException {
		// TODO Auto-generated method stub
		NameCallback name = new NameCallback("Name:     ");
		PasswordCallback pass = new PasswordCallback("Password: ", false);
		try {
			callbackHandler.handle(new Callback[] {name, pass});
		} catch (IOException e) {
			e.printStackTrace();
			return false;
		} catch (UnsupportedCallbackException e) {
			e.printStackTrace();
			return false;
		}
		accountName = name.getName();
		password = new String(pass.getPassword());
		return true;
	}

	@Override
	public boolean logout() throws LoginException {
		// TODO Auto-generated method stub
		System.err.println("LoginModule logout " );
		return false;
	}

}
